#include "Train.h"

/* CONSTRUCTOR */
Train::Train(TrainListener* trainListener, TrainData trainData)
{
  m_listener = trainListener;
  m_id = trainData.getId();
  m_potentiometer = new Potentiometer(this, trainData.getPotentiometerPort());
  m_pushButton = new PushButton(this, trainData.getPushButtonPort());
  m_LED = new LED(trainData.getLEDPort());
  m_lastCommandIsNullSpeed = false;
  m_LED->turnON();    // Led ON
}

/* METHODES */
/**
* \brief Processing for switch position evolution
* \param state
* \return none
*/
void Train::potentiometerPositionChanged(int value)
{
  byte command = 0x00;
  boolean moveForward = true;
  if(value < 480)
  { 
    command = 255 - value/2;
  }
  else /* value >= 480 */
  {
    if (value > 544)
    {
       command = value/2 - 256;
       moveForward = false;
    }
    else /* 480 <= value <= 544 */
    {
       moveForward = false;
    }
  }
  
  if(command != 0x00)
  {
    m_lastCommandIsNullSpeed = false;
    m_listener->trainSpeedHasChanged(m_id, moveForward, command);
  }
  else /* command == 0x00 */
  {
    if(m_lastCommandIsNullSpeed == true)
    {
      /* Speed = 0 has already been sent last time */
    }
    else
    {
      m_lastCommandIsNullSpeed = true;
      m_listener->trainSpeedHasChanged(m_id, moveForward, command);
    }
  }
}

/**
* \brief Processing for switch position evolution
* \param state
* \return none
*/
void Train::pushButtonPositionChanged(boolean state)
{
  if (state == false)
  {
//    m_listener->trainSmokeHasChanged(m_id, 0xFF);
    m_LED->turnON();    // Led ON
  }
  else
  {
//    m_listener->trainSmokeHasChanged(m_id, 0x00);
    m_LED->turnOFF();    // Led ON
  }
}

/**
* \brief Processing for switch rail command accepted
* \param none
* \return none
*/
void Train::trainCommandAccepted()
{
  m_LED->turnON();    // Led ON
}

/**
* \brief Processing for switch rail command delayed
* \param none
* \return none
*/
void Train::trainCommandAdapted()
{
  m_LED->blink(500);    // Led blink
}

/**
* \brief Get switch rail Id
* \param none
* \return id
*/
byte Train::getId()
{
  return m_id;
}
